package chatServer

import (
	"net"
	"fmt"
	"time"
)

type Agent struct {
	conn net.Conn
	room *Room
	uuid int64
	in   Message
	out  Message
}

func NewAgent(conn net.Conn, room *Room) (agent *Agent) {
	t := time.Now()
	agent = &Agent{
		conn:conn,
		room:room,
		uuid:t.Unix(),
		in:make(Message),
		out:make(Message),
	}
	room.accept(agent)
	go agent.run()
	go agent.listen()
	fmt.Println("new agent coming")
	return
}

func (agent *Agent) receive(msg string) {
	fmt.Printf("%s receive msg: %s", agent.uuid, msg)
	agent.room.message <- msg
}
func (agent *Agent) sendMsg(msg string) {
	agent.conn.Write([]byte(msg))
}

func (agent *Agent) listen() {
	for {
		select {
		case in := <-agent.in:
			agent.receive(in)
		case out := <-agent.out:
			agent.sendMsg(out)
		}
	}
}

func (agent *Agent) run() {
	var buf [512]byte
	for {

		n, _ := agent.conn.Read(buf[0:])
		fmt.Println(string(buf[0:n]))
		agent.in <- string(buf[0:n])
	}
}

